package com.study.fetch.rk;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.study.dto.TencentDTO.TenTool;
import com.study.fetch.rk.DataDTO.TxzxgData;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.Test;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhuzi
 * 2025/1/22 20:11
 */
public class Holiday {

    @Test
    public void holiday() {
        int year = LocalDate.now().getYear();
        for (int i = 1; i < 30; i++) {


            String url = "https://timor.tech/api/holiday/year/{}";
            String block = TenTool.webClient.get().uri(StrUtil.format(url, year))
                    .header("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0")
                    .retrieve().bodyToMono(String.class)//
                    .timeout(Duration.ofSeconds(8)).retry(3).block();

            JSONObject jsonObject = JSON.parseObject(block);
            Collection<Object> holiday = jsonObject.getJSONObject("holiday").values();
            for (Object o : holiday) {
                JSONObject jsObj = JSON.parseObject(o.toString());
                if (StrUtil.equalsAny(jsObj.getString("name"), "春节", "初一")) {
                    System.out.println(jsObj.getString("date"));
                }

            }
            year = year - i;
        }
    }

    /**
     * 计算春节之后第一个交易日｜1月到2月，日期相差大于7就是第一个交易日
     */
    @Test
    public void calcFirstFromNewYear() {
        String s = FileUtil.readUtf8String("/Users/zhuzi/Desktop/pics/A-统计/春节指数3天涨幅/data.json");
        List<TxzxgData> txzxgData = JSON.parseArray(s, TxzxgData.class);

        Map<Integer, List<LocalDate>> yearMap = txzxgData.stream().map(TxzxgData::getDate).distinct()
                .collect(Collectors.groupingBy(ia -> ia.getYear()));
        ArrayList<LocalDate> firstList = Lists.newArrayList();
        yearMap.forEach((k, v) -> {
            Collections.sort(v);
            List<LocalDate> mm = v.stream().filter(ib ->
                    StringUtils.equalsAny(ib.format(DateTimeFormatter.ofPattern("MM")), "01", "02")
            ).collect(Collectors.toList());
            Collections.sort(mm);

            for (int i = 0; i < mm.size() - 1; i++) {
                //间隔大于7天就算输出
                long daysBetween = ChronoUnit.DAYS.between(mm.get(i), mm.get(i + 1));
                if (daysBetween >= 7) {
                    firstList.add(mm.get(i + 1));
                }
            }
        });

        Collections.sort(firstList);
        for (LocalDate date : firstList) {
            System.out.println(date);
        }
    }
}
